/*
 * @Author: 郑刘利
 * @Date: 2020-03-12 16:31:14
 * @LastEditors: 郑刘利
 * @LastEditTime: 2020-03-18 17:50:32
 * @Description: file content
 * @FilePath: \one_project\src\store\index.ts
 */

import { observable, autorun, action } from 'mobx';
import { Music } from '../core/domain/fm/Music';

/**
 * 音乐播放的story
 */

const playerId = '__player__';
class VoicePlayer {
    private static _instance: VoicePlayer;
    public static get instance() {
        return this._instance ? this._instance : new VoicePlayer();
    }
    // 监听music列表
    @observable public musics: Music[] = [];
    @observable public index = 0;
    @observable public isPlayed = false;
    public audioElement: HTMLAudioElement;
    private constructor() {
        const player = document.createElement('audio');
        player.id = playerId;
        player.style.display = 'none';
        player.autoplay = false;
        document.body.appendChild(player);

        this.audioElement = player;
    }
    @action public next() {
        if (this.musics.length === 0) {
            this.index = -1;
            return;
        }
        this.index++;
        if (this.index === this.musics.length) {
            this.index = 0;
        }
    }
    @action public prev() {
        if (this.musics.length === 0) {
            this.index = -1;
            return;
        }
        this.index--;
        if (this.index === -1) {
            this.index = this.musics.length - 1;
        }
    }
    @action public play() {
        this.isPlayed = true;
    }
    @action public pause() {
        this.isPlayed = false;
    }
}
const voicePlayer = VoicePlayer.instance;

// store播放状态改变时 同步播放器的状态
autorun(() => {
    if (voicePlayer.isPlayed === true) {
        voicePlayer.audioElement.play();
    } else {
        voicePlayer.audioElement.pause();
    }
});

// index 变更自动播放对应音乐
autorun(() => {
    const src = voicePlayer.musics[voicePlayer.index]?.url;
    if (src && src !== voicePlayer.audioElement.src) {
        voicePlayer.audioElement.src = src;
    } else {
        voicePlayer.audioElement.pause();
    }
});
export default voicePlayer;
